import { Model, DataTypes, Optional } from 'sequelize';
import sequelize from '@/config/database';

// 定义登录日志属性接口
interface LoginInfoAttributes {
  infoId: number;
  userName: string;
  status: string;
  ipaddr: string;
  loginLocation: string;
  browser: string;
  os: string;
  msg: string;
  loginTime: Date;
}

// 创建时可选字段
interface LoginInfoCreationAttributes extends Optional<LoginInfoAttributes, 'infoId'> {}

// 登录日志模型
class LoginInfo extends Model<LoginInfoAttributes, LoginInfoCreationAttributes> implements LoginInfoAttributes {
  public infoId!: number;
  public userName!: string;
  public status!: string;
  public ipaddr!: string;
  public loginLocation!: string;
  public browser!: string;
  public os!: string;
  public msg!: string;
  public loginTime!: Date;

  // 时间戳
  public readonly createTime!: Date;
  public readonly updateTime!: Date;

  // 状态常量
  public static readonly STATUS = {
    SUCCESS: '0',  // 成功
    FAIL: '1'      // 失败
  };
}

LoginInfo.init(
  {
    infoId: {
      type: DataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
      field: 'info_id',
      comment: '访问ID'
    },
    userName: {
      type: DataTypes.STRING(50),
      allowNull: false,
      defaultValue: '',
      field: 'user_name',
      comment: '用户账号'
    },
    status: {
      type: DataTypes.CHAR(1),
      allowNull: false,
      defaultValue: '0',
      field: 'status',
      comment: '登录状态 0成功 1失败'
    },
    ipaddr: {
      type: DataTypes.STRING(128),
      allowNull: true,
      defaultValue: '',
      field: 'ipaddr',
      comment: '登录IP地址'
    },
    loginLocation: {
      type: DataTypes.STRING(255),
      allowNull: true,
      defaultValue: '',
      field: 'login_location',
      comment: '登录地点'
    },
    browser: {
      type: DataTypes.STRING(50),
      allowNull: true,
      defaultValue: '',
      field: 'browser',
      comment: '浏览器类型'
    },
    os: {
      type: DataTypes.STRING(50),
      allowNull: true,
      defaultValue: '',
      field: 'os',
      comment: '操作系统'
    },
    msg: {
      type: DataTypes.STRING(255),
      allowNull: true,
      defaultValue: '',
      field: 'msg',
      comment: '提示消息'
    },
    loginTime: {
      type: DataTypes.DATE,
      allowNull: true,
      field: 'login_time',
      comment: '访问时间'
    }
  },
  {
    sequelize,
    tableName: 'sys_logininfor',
    timestamps: false,
    indexes: [
      {
        name: 'idx_sys_logininfor_s',
        fields: ['status']
      },
      {
        name: 'idx_sys_logininfor_lt',
        fields: ['login_time']
      }
    ]
  }
);

export default LoginInfo; 